<?php

namespace App\Admin\Controllers;

use App\Http\Traits\GlobalConstant;
use App\Models\Campus;
use App\Models\Shop;
use App\Models\Users;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class ShopController extends BaseController
{
    const   INVITE_STATUS = [
        'on'  => ['value' => 1, 'text' => '正常', 'color' => 'default'],
        'off' => ['value' => 0, 'text' => '禁用', 'color' => 'danger'],
    ];

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('店铺列表')
            ->description(' ')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('店铺详情')
            ->description(' ')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑店铺')
            ->description(' ')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新增店铺')
            ->description('新增店铺')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Shop());
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1 / 2, function ($filter) {
                $filter->like('name', '店铺名称');

            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('status', '状态')->select(['禁用', '正常']);
            });

        });
        $grid->model()->orderBy('id', 'desc');
        $grid->column('id', 'ID')->sortable();
        $grid->column('name', '店铺名称');
        $grid->column('userInfo.nickname','关联用户');
        $grid->column('logo','logo')->lightbox(['width' => 30, 'height' => 30]);
        $grid->column('contact','联系电话');
        $grid->column('address', '地址');
        $grid->column('status', __('状态'))->switch(self::INVITE_STATUS);
        $grid->column('created_at', __('created_at'));
        $grid->column('updated_at', __('updated_at'));

        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();

        });
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        Admin::style('.img-thumbnail {width: 60px;height:60px}');
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Shop::findOrFail($id));

        $show->panel()
            ->tools(function ($tools) {
                $tools->disableDelete();
            });
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = 0)
    {
        $form = new Form(new Shop());
        $form->text('name', '店铺名称')->required();
        $form->text('contact', '联系电话')->required();
//        $form->select('user_id','关联用户')->required()->options(Users::where('status',1)->pluck('nickname as text','id'))
//            ->creationRules(['required', "unique:shop"],['unique'=>'当前选择的用户已被关联'])
//            ->updateRules(['required', "unique:shop,user_id,{{id}}"],['unique'=>'当前选择的用户已被关联']);
        $form->select('user_id','关联用户')->required()->options(Users::where('status',1)->pluck('nickname as text','id'));
        $form->image('logo', 'logo')->required()->uniqueName();
        $form->text('address', '地址')->required();
        $html =<<<html
        <script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=XFVBZ-ICDYW-GI4R6-YTUJD-3ZBC3-YJBIJ"></script>
        <div style="height: 600px;" id="container"></div>
html;
        $form->hidden('latitude','纬度')->attribute(['id'=>'latitude'])->default('29.560317');;
        $form->hidden('longitude','经度')->attribute(['id'=>'longitude'])->default('106.507965');
        $script1 = <<<SCRIPT
             var lat = $('#latitude');
             var lng = $('#longitude');
             var center = new qq.maps.LatLng(lat.val(), lng.val());
             var container = document.getElementById("container");
             var map = new qq.maps.Map(container, {
                center: center,
                zoom: 16
             });
              var marker = new qq.maps.Marker({
                    position: center,
                    draggable: true,
                    map: map
                });

                if( ! lat.val() || ! lng.val()) {
                    var citylocation = new qq.maps.CityService({
                        complete : function(result){
                        map.setCenter(result.detail.latLng);
                        marker.setPosition(result.detail.latLng);
                    }
                    });

                    citylocation.searchLocalCity();
                }

                qq.maps.event.addListener(map, 'click', function(event) {
                    marker.setPosition(event.latLng);

                });

                qq.maps.event.addListener(marker, 'position_changed', function(event) {
                    var position = marker.getPosition();
                    lat.val(position.getLat());
                    lng.val(position.getLng());
                });
                $('#address').blur(function(){
                    let kw = $(this).val();
                    $.ajax({
                        url: '/api/platform/get_map_search',
                        type: 'get',
                        data: {kw:kw},
                        dataType: 'json',
                        timeout: 2000,
                        success: function (res) {
                            if (res.code == 0&&res.data.lat!='') {
                                console.log(res)
                                var latLng=new qq.maps.LatLng(res.data.lat,res.data.lng);
                                map.setCenter(latLng);
                                marker.setPosition(latLng);
                            }
                        },
                        error: function () {
                            alert('未能找到地址')
                        }
                 });
                })



SCRIPT;
        Admin::script($script1,true);

        $form->html($html,'店铺位置');
        $form->radio('status', '状态')->options([0 => '禁用', 1 => '正常'])->default(1);
        $form->tools(function (Form\Tools $tools) {
            // 去掉`删除`按钮
            $tools->disableDelete();
            $tools->disableView();
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        return $form;
    }

}
